<script lang="ts">
import navi from "@/components/userNavi.vue";
import {computed, onMounted, reactive, Ref, ref} from "vue";
import request from "@/utils/request";
import {rules} from "@typescript-eslint/eslint-plugin";
import {ElMessage, FormInstance, FormRules} from "element-plus";
export default {
  components:{
    navi
  },
  setup(){
    const list: Ref<{status: string}[]> = ref([]);
    const formLabelWidth = '100px'
    const dialogFormVisible=ref(false)
    const total = ref('')
    const custId=ref('')
    const params = ref({
      page: 1,
      size: 10
    })
    const formRef=ref<FormInstance>()
    const form=reactive({
      commentData:'',
      commentScore:0,
      proId:'',
      custId:''
    })

    const rules=reactive<FormRules>({
      commentData: [
        { required: true, message: '评论不可为空', trigger: 'blur' }],
      commentScore: [
        { required: true, message: '请选择评分', trigger: 'blur' }]
    })

    interface Order {
      date: string
      name: string
      address: string
    }


    onMounted(()=>{
      let item = localStorage.getItem("custId");
      try {
        custId.value = item ? JSON.parse(item) : null;
        form.custId=custId.value;
      } catch (error) {
        console.error('Error parsing JSON:', error);
      }
      pagehelper()
      console.log(list)
    })
    const pagehelper = async () => {
      const res = await request.get(`/order/page/${custId.value}/${params.value.page}/${params.value.size}`)
      console.log("分页页面")
      console.log(res.data)
      console.log("分页后")
      list.value= res.data.data.records
      console.log(list.value)
      total.value =res.data.data.total
      console.log(total.value)
    }


    const handleEdit = (index: number, row: Order) => {
      console.log(index, row)
    }
    const handleDelete = (index: number, row: Order) => {
      console.log(index, row)
    }
    const handleSizeChange = (val: number) => {
      console.log(`每页 ${val} 条`)
      params.value.size = val
      pagehelper()
    }

    const handleCurrentChange = (val: number) => {
      console.log(`当前页: ${val}`)
      params.value.page = val
      pagehelper()
    }
    const value=ref("")
    const options = [
      {
        value: '未支付',
        label: '未支付',
      },
      {
        value: '已支付',
        label: '已支付',
      }

    ]
    const filterTableData = computed(() =>{
          console.log(list)
      // 如果没有选择状态，返回所有数据
        if(value.value===""){
          return null
        }else {
          return list.value.filter(item => item.status === value.value)
        }
    }
    )
    const filterData=()=>{
      filterTableData.value
    }


    const goToComment = async (row:any) => {
      form.proId=row.proId
      dialogFormVisible.value=true
    }

    const addComments = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate(async (valid, fields) => {
        if (valid) {
          const res=await request.post(`/addComments`, form)
          console.log('submit!')
          console.log(res.data.data)
          dialogFormVisible.value=false
          formEl.resetFields()
        } else {
          console.log('error submit!', fields)
        }
      })

    }
    return{
      handleEdit,
      handleDelete,
      pagehelper,
      onMounted,
      form,
      formRef,
      custId,
      list,
      params,
      total,
      rules,
      handleSizeChange,
      handleCurrentChange,
      value,
      options,
      filterTableData,
      filterData,
      dialogFormVisible,
      formLabelWidth,
      addComments,
      goToComment
    }
  }
}
</script>

<template>
  <div class="orderPage">
    <navi/>
    <el-table :data="filterTableData?filterTableData:list" border style="width: 100%">
      <el-table-column label="订单创建日期" prop="orderCreateTime" />
      <el-table-column label="编号" prop="orderNumber" />
      <el-table-column label="价格" prop="orderPrice"/>
      <el-table-column label="状态" prop="status"/>
      <el-table-column align="right" width="200px">
        <template #header>
          <el-select v-model="value" filterable placeholder="Select" @change="filterData">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </template>
        <template #default="scope">
          <router-link :to="{path:`/order/${scope.row.orderNumber}`}">
          <el-button type="primary" size="small" v-if="scope.row.status==='未支付'" @click="handleEdit(scope.$index, scope.row)">去支付
          </el-button>
          </router-link>
          <el-button type="primary" size="small" v-if="scope.row.status==='已支付'" @click="goToComment(scope.row)">去评论
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="page"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="this.params.page"
                   :page-sizes="10"
                   :page-size="this.params.size"
                   layout=" prev, pager, next, jumper"
                   :total="this.total">
    </el-pagination>
  </div>

  <el-dialog v-model="dialogFormVisible" title="评论">
    <el-form ref="formRef" :model="form" :rules="rules">

      <el-form-item label="评分" :label-width="formLabelWidth" prop="commentScore">
        <el-rate v-model="form.commentScore" size="large"  allow-half />
      </el-form-item>

      <el-form-item label="发表评论" :label-width="formLabelWidth" prop="commentData" >
        <el-input v-model="form.commentData"
                  autocomplete="off"
                  placeholder="在此输入评论"
                  :autosize="{ minRows: 3, maxRows: 4 }"
                  type="textarea"
        />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addComments(formRef)">
          Confirm
        </el-button>
      </span>
    </template>
  </el-dialog>


</template>

<style scoped>
.orderPage{
  width: 1400px;
  margin: auto;
}
</style>